import editForm from "../form.vue";
import { message } from "@/utils/message";
import { addDialog } from "@/components/ReDialog";
import type { FormItemProps } from "./types";
import type { PaginationProps } from "@pureadmin/table";

import {
  deviceDetection,
  cloneDeep,
  isAllEmpty,
  getKeyList
} from "@pureadmin/utils";
import { list, create, update, remove } from "@/api/drafts";
import { detail } from "@/api/drafts_config";

import { reactive, ref, onMounted, h, toRaw } from "vue";
import { ElMessageBox } from "element-plus";
import { usePublicHooks } from "@/views/common/hooks";
import { useUserStore } from "@/store/modules/user";
import { useAdminHooks } from "@/views/common/admin";
import { handleTree } from "@/utils/tree";
import ConfigForm from "@/views/drafts_config/form.vue";
import ConfigLogsForm from "@/views/drafts_config/logs.vue";
import { classify as configClassify } from "@/views/drafts_config/utils/hook"; // 导入 config 的 hook

export function classify(tableRef: Ref) {
  const titleMenu = "草稿箱";
  const userStore = useUserStore();
  const { adminList, isSuperAdmin } = useAdminHooks();

  const initialForm = {
    search_type: "",
    search: "",
    limit: 20,
    page: 1,
    type: "business"
  };

  const form = reactive({ ...initialForm });
  const curRow = ref();
  const formRef = ref();
  const dataList = ref([]);
  const detailConfig = ref([]);
  const isShow = ref(false);
  const loading = ref(true);
  const switchLoadMap = ref({});
  const { switchStyle } = usePublicHooks();

  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 20,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "勾选列", // 如果需要表格多选，此处label必须设置
      type: "selection",
      fixed: "left"
    },
    {
      label: "ID",
      prop: "id"
    },
    {
      label: "标题",
      prop: "title"
    },
    {
      label: "类型分类名称",
      prop: "type_classify_title"
    },
    {
      label: "业务分类名称",
      prop: "business_classify_title"
    },
    {
      label: "SEO描述",
      prop: "seo_desc"
    },
    {
      label: "SEO关键词",
      prop: "seo_keyword"
    },
    {
      label: "描述",
      prop: "content",
      hide: true
    },
    {
      label: "正文",
      prop: "text",
      hide: true
    },
    {
      label: "生成时间",
      prop: "created_at",
      minWidth: 160
    },
    {
      label: "操作",
      fixed: "right",
      width: 210,
      slot: "operation"
    }
  ];

  function handleSizeChange(val: number) {
    form.limit = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    form.page = val;
    onSearch();
  }

  async function onSearch() {
    loading.value = true;
    const params: Record<string, any> = {
      page: form.page,
      limit: form.limit,
      type: form.type
    };

    if (form.search_type !== "") {
      params[form.search_type] = form.search;
    }

    const { data } = await list(toRaw(params));
    let newData = data.list;
    if (!isAllEmpty(form.search_type)) {
      if (form.search_type === "title") {
        // 前端搜索
        newData = newData.filter(item => item.title.includes(form.search));
      }
      if (form.search_type === "type") {
        // 前端搜索
        newData = newData.filter(item => item.type.includes(form.search));
      }
    }

    dataList.value = handleTree(newData, "id", "parent_id"); // 处理成树结构

    pagination.total = data.total;
    pagination.pageSize = data.limit;
    pagination.currentPage = data.page;

    const { data: configData } = await detail({ id: 1 });
    detailConfig.value = configData;

    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();

    Object.keys(form).forEach(key => {
      if (!(key in initialForm)) {
        delete form[key];
      }
    });

    Object.assign(form, initialForm);

    onSearch();
  };

  function openDialog(title = "新增", row?: FormItemProps) {
    addDialog({
      fullscreenIcon: true,
      title: `${title}${titleMenu}`,
      props: {
        formInline: {
          id: row?.id ?? 0,
          type_classify_id: row?.type_classify_id ?? 0,
          business_classify_id: row?.business_classify_id ?? 0,
          title: row?.title ?? "",
          seo_desc: row?.seo_desc ?? "",
          seo_keyword: row?.seo_keyword ?? "",
          content: row?.content ?? "",
          text: row?.text ?? ""
        }
      },
      width: "40%",
      draggable: true,
      fullscreen: deviceDetection(),
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`您修改了生成文章配置`, {
            type: "success"
          });
          done();
          onSearch();
        }
        FormRef.validate(valid => {
          if (valid) {
            update(curData).then(res => {
              if (res.success) {
                chores();
              } else {
                message(res.message, { type: "error" });
              }
            });
          }
        });
      }
    });
  }

  /** 高亮当前权限选中行 */
  function rowStyle({ row: { id } }) {
    return {
      cursor: "pointer",
      background: id === curRow.value?.id ? "var(--el-fill-color-light)" : ""
    };
  }

  onMounted(async () => {
    onSearch();
  });

  function onChangeStatus({ row, index }) {
    ElMessageBox.confirm(
      `确认要 < strong > ${row.status === 0 ? "停用" : "启用"}</strong > AI云监理：<strong style='color:var(--el-color-primary)'>${row.address}</strong>吗 ? `,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(() => {
        updateStatus(row).then(res => {
          if (res.success) {
            switchLoadMap.value[index] = { loading: true };
            setTimeout(() => {
              switchLoadMap.value[index] = { loading: false };
              message("已成功修改状态", { type: "success" });
            }, 300);
          } else {
            message(res.message, { type: "error" });
          }
        });
      })
      .catch(() => {
        row.status = row.status === 0 ? 1 : 0;
      });
  }

  function handleDelete(row) {
    remove({ id: [row.id] }).then(res => {
      if (res.success) {
        message(`您删除了${titleMenu}：${row.title}`, {
          type: "success"
        });
        onSearch();
      } else {
        message(res.message, { type: "error" });
      }
    });
  }

  const selectedNum = ref(0);

  /** 当CheckBox选择项发生变化时会触发该事件 */
  function handleSelectionChange(val) {
    selectedNum.value = val.length;
    // 重置表格高度
    tableRef.value.setAdaptive();
  }

  /** 取消选择 */
  function onSelectionCancel() {
    selectedNum.value = 0;
    // 用于多选表格，清空用户的选择
    tableRef.value.getTableRef().clearSelection();
  }

  /** 批量删除 */
  function onbatchDel() {
    // 返回当前选中的行
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    remove({ id: getKeyList(curSelected, "id") }).then(res => {
      if (res.success) {
        message(`已删除编号为 ${getKeyList(curSelected, "id")} 的数据`, {
          type: "success"
        });
        tableRef.value.getTableRef().clearSelection();
        onSearch();
      } else {
        message(res.message, { type: "error" });
      }
    });
  }

  // 实例化 config 的 hook
  const configHook = configClassify(tableRef);

  function openConfigDialog() {
    addDialog({
      title: "生成文章配置",
      width: "40%",
      draggable: true,
      fullscreen: deviceDetection(),
      props: {
        formInline: configHook.detailConfig.value // 使用 config 的数据
      },
      contentRenderer: () => h(ConfigForm, { ref: configHook.formRef }), // 使用 config 的 ref
      beforeSure: configHook.handleSubmit
    });
  }

  function openConfigLogsDialog() {
    addDialog({
      title: "生成文章记录",
      width: "1000px",
      fullscreenIcon: true,
      contentRenderer: () => h(ConfigLogsForm),
      footer: false
    });
  }

  return {
    titleMenu,
    form,
    isShow,
    loading,
    columns,
    rowStyle,
    dataList,
    pagination,
    onSearch,
    resetForm,
    openDialog,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange,
    handleDelete,
    selectedNum,
    onSelectionCancel,
    onbatchDel,
    openConfigDialog,
    openConfigLogsDialog
  };
}
